<template>
  <div class="search_advanced_box">
    <div class="searchbox_a">
      <div class="search_icon">
        <img :src="searchIcon">
      </div>
    </div>
    <div class="searchbox_b">
      <div>
        <div class="B-searIcoLs">
          <kbd @click="typeYbKbd('socialaccount')" :class="{active:belongGroup=='socialaccount'}">
            <strong>
              <i class="icon iconfont icon-zhanghaoguanli"></i>
            </strong>
            <span>实体</span>
          </kbd>
          <kbd @click="typeYbKbd('socialdynamic')" :class="{active:belongGroup=='socialdynamic'}">
            <strong>
              <i class="icon iconfont icon-shuoming"></i>
            </strong>
            <span>事件</span>
          </kbd>
          <kbd @click="typeYbKbd('keyfigures')" :class="{active:belongGroup=='keyfigures'}">
            <strong>
              <i class="icon iconfont icon-mingdanfenpei"></i>
            </strong>
            <span>重点人物</span>
          </kbd>
          <kbd @click="typeYbKbd('focusgroup')" :class="{active:belongGroup=='focusgroup'}">
            <strong>
              <i class="icon iconfont icon-zuzhixietiaonengli"></i>
            </strong>
            <span>重点组织</span>
          </kbd>
          <kbd @click="typeYbKbd('document')" :class="{active:belongGroup=='document'}">
            <strong>
              <i class="icon iconfont icon-wendang3"></i>
            </strong>
            <span>文档</span>
          </kbd>
          <kbd @click="typeYbKbd('media')" :class="{active:belongGroup=='media'}">
            <strong>
              <i class="icon iconfont icon-duomeit"></i>
            </strong>
            <span>多媒体</span>
          </kbd>
          <kbd class="enter">
            <el-button type="primary" class="in-searEnt" @click="handlerSearch">
              <i class="icon iconfont icon-search2"></i>
              搜索</el-button>
            <span class="qt-search" @click="commonSearch">普通搜索
              <i class="icon iconfont icon-qianjin"></i>
            </span>
          </kbd>
        </div>
      </div>
      <!-- 高级搜索表单内容 -->
      <div>
        <el-button type="primary" plain @click="addSearchObj" class="add-btn" :disabled="objectList.length>0">添加搜索对象</el-button>
        <div class="clear"></div>
        <div v-for="(object,index) in objectList" :key="index" class="object-box">
          <div class="objectname-box">
            <span class="name">对象名称:</span>
            <el-input class="objectname-input" v-model="object.objectName" readonly></el-input>
            <el-button plain @click="addCondition(index)">添加属性条件</el-button>
            <i class="el-icon-error" title='删除对象' @click="deleteObj(index)"></i>
          </div>
          <div v-for="(condition,index) in object.conditions" :key="index" class="property-box">
            <span class="name">属性名称:</span>
            <el-select v-model="condition.propertyUri" placeholder="请选择" @change="select_property(object.conditions,index,object.allConditions)">
              <el-option v-for="(item,index) in object.allConditions" :key="index" :label="item.displayname" :value="item.propertyUri">
              </el-option>
            </el-select>
            <template v-if="condition.propertyUri!=''">
              <template v-if="condition.propertyType==='GisData'">
                <span>
                  <el-select v-model="condition.comparison" placeholder="请选择">
                    <el-option v-for="(item,index) in comparison_option_str" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input class="propertyValin-T" v-model="condition.value.address" style="width:30%" :placeholder="'请输入'+condition.displayname" />
                </span>
              </template>
              <template v-else-if="condition.propertyType==='TimeInterval'">
                <span>
                  <el-date-picker v-model="condition.value.timeStart" type="datetime" placeholder="开始时间" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                  <span>至</span>
                  <el-date-picker v-model="condition.value.timeEnd" type="datetime" placeholder="开始时间" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </span>
              </template>
              <template v-else-if="condition.propertyType==='DateTime'">
                <span>
                  <el-select v-model="condition.comparison" placeholder="请选择">
                    <el-option v-for="(item,index) in comparison_option_number" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <el-date-picker v-model="condition.value" type="datetime" :placeholder="'请输入'+condition.displayname" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </span>
              </template>
              <template v-else-if="condition.propertyType==='String'">
                <span>
                  <el-select v-model="condition.comparison" placeholder="请选择">
                    <el-option v-for="(item,index) in comparison_option_str" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input class="propertyValin-T" v-model="condition.value" style="width:20%" :placeholder="'请输入'+condition.displayname" />
                </span>
              </template>
              <template v-else>
                <span>
                  <el-select v-model="condition.comparison" placeholder="请选择">
                    <el-option v-for="(item,index) in comparison_option_number" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input class="propertyValin-T" v-model="condition.value" style="width:20%" :placeholder="'请输入'+condition.displayname" />
                </span>
              </template>
            </template>
            <i class="el-icon-error" title='删除属性' @click="deletePro(object.conditions,index)"></i>
          </div>
          <div class="tags-box">
            <span class="name">选择标签:</span>
            <div class="all-tags">
              <div v-for="tag in object.Alltags" :key="tag.id" class="tag-search">
                <el-checkbox v-model="tag.isChecked"></el-checkbox>
                <span @click="tag.isChecked=!tag.isChecked">{{tag.displayname}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--选择对象弹出框-->
    <el-dialog title="选择分组" :visible.sync="dialogObjctVisible" :append-to-body='true'>
      <el-tree ref="tree" :props="defaultProps" :render-content="renderContent" :default-expand-all="true" :expand-on-click-node='false' @node-click="handlerNodeClick" :data="treeData">
      </el-tree>
    </el-dialog>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import searchIcon from '@/images/search-icon.png'
import util from '@/utils'
import {
    getTags,
    getObjectTreeByType,
    getObjectPropertiesByUri,
    findAllWithBizGroupAsMap
} from '@/api/search'
export default {
    data () {
        return {
            searchIcon,
            // 类别
            type: 'Entity',
            belongGroup: 'socialaccount',
            enterType: 'Entity',
            propertyList: [],
            // 当前选择对象的uri
            current_uri: '',
            // 对象数组(高级搜索)
            // 当前对象数组索引(高级搜索)
            currentObj_index: -1,
            // 当前属性数组索引(高级搜索)
            currentProp_index: -1,
            dialogObjctVisible: false,
            // 对象树数据
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            // 比较符选项(数值)
            comparison_option_number: [
                { label: '小于', value: '<' },
                { label: '小于等于', value: '<=' },
                { label: '等于', value: '=' },
                { label: '大于', value: '>' },
                { label: '大于等于', value: '>=' }
            ],
            // 比较符选项(字符串)
            comparison_option_str: [
                { label: '精确查询', value: '=' },
                { label: '模糊查询', value: '%' }
            ],
            // 搜索条件列表
            objectList: [],
            // 请求到的标签列表
            tagsList: []
        }
    },
    watch: {
        $route (to, from) {
            if (to.path === '/advanced-search') {
                Cookies.remove('queryCriteria')
            }
        }
    },
    mounted () {
        this.getTags()
    },
    methods: {
    // 搜索
        handlerSearch () {
            // 判断类型数组是否为空
            if (this.objectList.length === 0) {
                this.$message.error(`请选择搜索对象`)
                return false
            }
            // 判断属性
            for (let item of this.objectList) {
                if (
                    item.conditions.length === 0 ||
          (item.conditions.length === 1 &&
            item.conditions[0].propertyUri === '')
                ) {
                    this.$message.error(`${item.objectName} 至少选择一个属性`)
                    return false
                } else {
                    for (let c of item.conditions) {
                        if (c.propertyType === 'GisData') {
                            if (c.comparison === '' || c.address === '') {
                                this.$message.error(`请输入${c.displayname}的查询条件`)
                                return false
                            }
                        } else if (c.propertyType === 'TimeInterval') {
                            if (c.timeStart === '' || c.timeEnd === '') {
                                this.$message.error(`请输入${c.displayname}的查询条件`)
                                return false
                            }
                        } else {
                            if (c.comparison === '' || c.value === '') {
                                this.$message.error(`请输入${c.displayname}的查询条件`)
                                return false
                            }
                        }
                    }
                }
            }
            let paramsObj = this.objectList.map(item => {
                let obj = {
                    objectUri: item.objectUri,
                    conditions: [],
                    tags: [],
                    objectName: item.objectName
                }
                for (let t of item.Alltags) {
                    if (t.isChecked) {
                        obj.tags.push(t.displayname)
                    }
                }
                for (let c of item.conditions) {
                    let conObj = {
                        propertyUri: c.propertyUri,
                        propertyType: c.propertyType,
                        displayname: c.displayname
                    }
                    if (c.propertyType === 'GisData') {
                        conObj.comparison = c.comparison
                        conObj.address = c.value.address
                    } else if (c.propertyType === 'TimeInterval') {
                        conObj.timeStart = new Date(c.value.timeStart).getTime()
                        conObj.timeEnd = new Date(c.value.timeEnd).getTime()
                    } else if (c.propertyType === 'DateTime') {
                        conObj.comparison = c.comparison
                        conObj.value = new Date(c.value).getTime()
                    } else {
                        conObj.comparison = c.comparison
                        conObj.value = c.value
                    }
                    obj.conditions.push(conObj)
                }
                return obj
            })
            console.log(paramsObj)
            // return
            // 存储查询条件
            Cookies.set(
                'queryCriteria',
                JSON.stringify({
                    type: this.type,
                    belongGroup: this.belongGroup,
                    objectList: paramsObj
                })
            )
            this.$router.push({
                path: '/advanced-search-show'
            })
        },
        deleteObj (index) {
            this.objectList.splice(index, 1)
        },
        deletePro (conditions, index) {
            conditions.splice(index, 1)
        },
        // 普通搜索
        commonSearch () {
            this.$router.push('/search')
        },
        // 点击新增搜索对象
        addSearchObj () {
            let params = {
                groupList: [this.belongGroup]
            }
            findAllWithBizGroupAsMap(params).then(data => {
                this.treeData = util.parseKeyData(data)
                this.dialogObjctVisible = true
            })
        },
        // 添加属性搜索
        addCondition (index) {
            let hasNullProperty = false
            for (let item of this.objectList[index].conditions) {
                if (item.propertyUri === '') {
                    hasNullProperty = true
                    break
                }
            }
            if (hasNullProperty) {
                return false
            }
            this.objectList[index].conditions.push({ propertyUri: '' })
        },
        // 点击对象树节点
        handlerSearchObj (index) {
            this.currentObj_index = index
            this.dialogObjctVisible = true
            this.treeData = []
            let params = {
                groupList: [this.belongGroup]
            }
            findAllWithBizGroupAsMap(params).then(data => {
                this.treeData = util.parseKeyData(data)
            })
        },
        renderContent (h, { node, data }) {
            let currentStyle = `background:url(${
                data.icon
            }) 0 0 no-repeat;background-size: 16px 16px`
            return (
                <p>
                    <span style={currentStyle}>
                        <span style="margin-left:24px;">{node.label}</span>
                    </span>
                </p>
            )
        },
        // 树状菜单节点单击回调
        handlerNodeClick (data, node) {
            console.log(data)
            if (node.level === 1) {
                this.$message({ message: '不能选择根节点', type: 'error' })
                return false
            }
            for (let obj of this.objectList) {
                if (obj.objectUri === data.uri) {
                    this.$message({
                        message: '您已经选择该对象,请重新选择!',
                        type: 'warning'
                    })
                    return false
                }
            }
            let item = {
                objectUri: data.uri,
                objectName: data.displayname,
                conditions: []
            }
            this.$set(item, 'Alltags', JSON.parse(JSON.stringify(this.tagsList)))
            item.Alltags.forEach(item => {
                this.$set(item, 'isChecked', false)
            })
            this.objectList.push(item)
            this.dialogObjctVisible = false
            // 获取属性列表
            this.getPropertyList(this.objectList.length - 1)
        },
        getPropertyList (index) {
            // index objectList下标
            getObjectPropertiesByUri({ uri: this.objectList[index].objectUri }).then(
                response => {
                    response.data.forEach(item => {
                        if (item.propertyType === 'GisData') {
                            this.$set(item, 'value', { address: '' })
                            this.$set(item, 'comparison', '')
                        } else if (item.propertyType === 'TimeInterval') {
                            this.$set(item, 'value', { timeStart: '', timeEnd: '' })
                        } else {
                            this.$set(item, 'value', '')
                            this.$set(item, 'comparison', '')
                        }
                    })
                    this.objectList[index].allConditions = response.data
                }
            )
        },
        // 选择属性
        select_property (conditions, index, allConditions) {
            let propertyArr = conditions.map(item => {
                return item.propertyUri
            })
            function isRepeatFun (arr) {
                let hash = {}
                for (var i in arr) {
                    if (hash[arr[i]]) {
                        return true
                    }
                    hash[arr[i]] = true
                }
                return false
            }
            let isRepeat = isRepeatFun(propertyArr)
            if (isRepeat) {
                this.$message.error('该属性已标注,请重新选择!')
                this.$set(conditions[index], 'propertyUri', '')
            } else {
                for (let item of allConditions) {
                    if (item.propertyUri === conditions[index]['propertyUri']) {
                        for (let k in item) {
                            this.$set(conditions[index], k, item[k])
                        }
                    }
                }
            }
        },
        // 切换搜索类型
        typeYbKbd (belongGroup) {
            this.belongGroup = belongGroup
            this.objectList = []
        },
        getTags () {
            getTags().then(response => {
                this.tagsList = response.data
            })
        }
    }
}
</script>
<style lang="less" scoped>
@bg_img: url(../../images/search-back.jpg);
.el-dialog {
  width: 30%;
  .el-dialog__header {
    background-color: #157dd0;
    .el-dialog__title {
      color: #fff;
    }
  }
}
.search_advanced_box {
  background: @bg_img no-repeat center top;
  background-size: 100% auto;
  .searchbox_a {
    width: 800px;
    margin: auto;
    text-align: center;
    line-height: 48px;
    .search_icon {
      padding: 5% 0;
    }
  }

  .searchbox_b {
    width: 1000px;
    margin: auto;
    .el-input__inner {
      height: 32px;
    }
    .in-searEnt {
      height: 40px;
      padding: 0 24px;
      background-color: #1169c4;
      font-size: 1.2em;
      margin-top: 20px;
      .icon {
        margin-right: 5px;
      }
    }
    .qt-search {
      cursor: pointer;
      color: #2c3e50;
      margin-left: 12px;
    }
    .B-searIcoLs {
      text-align: center;
      margin-left: 20px;
      .active {
        color: #0d5fb4;
      }
      kbd {
        display: inline-block;
        width: 80px;
        height: 130px;
        margin: 0px 6px;
        text-align: center;
        color: #999;
        strong {
          display: block;
          font-weight: normal;
          height: 80px;
          i.icon {
            font-size: 40px;
            line-height: 100px;
          }
        }
      }
      kbd.enter {
        width: 210px;
        vertical-align: middle;
      }
    }
    .objUriClass {
      margin: 4px 0 4px 12px;
    }
    .add-btn{
      margin:-24px 0 10px 120px;
    }
  }
}
</style>
<style lang="less">
.object-box {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
  margin-left:45px;
  .name {
    margin-right: 10px;
  }
  .objectname-box {
    .objectname-input {
      display: inline-block;
      width: 50%;
    }
    .el-icon-error {
      margin-left: 5px;
      cursor: pointer;
    }
  }
  .property-box {
    margin-top: 20px;
    .el-icon-error {
      margin-left: 5px;
      cursor: pointer;
    }
  }
  .tags-box {
    margin-top: 20px;
    .all-tags {
      display: inline-block;
      max-height: 50px;
      overflow: visible;
      .tag-search {
        display: inline-block;
        margin: 5px;
        cursor: pointer;
      }
    }
  }
}
</style>
